import { createSlice } from "@reduxjs/toolkit";
import router from '@/router'
import type { tabitem } from '@/types/common'

interface tabState {
  tabsList: Array<tabitem>;
}
const initialState: tabState = {
  tabsList: [{ title: '首页', icon: 'HomeOutlined', path: '/', key: '/', isclose: false }],
}
// const navigate = useNavigate()
export const tabSlice = createSlice({
  name: 'tab',
  initialState,
  reducers: {
    add: (state, { payload }) => {
      const noTabber = ['/login', '*', '/reload'].includes(payload.key)
      const isFind = state.tabsList.some(item => item.key === payload.key)

      if (noTabber) return
      if (!isFind) state.tabsList.push({ ...payload, isclose: payload.path !== '/' })
    },
    remove: (state, { payload }) => {
      switch (payload.key) {
        case 'left':
          state.tabsList.splice(1, payload.removedindex)
          break
        case 'right':
          state.tabsList.splice(payload.removedindex + 1)
          break
        case 'other':
          state.tabsList = state.tabsList.filter(item => item.key === state.tabsList[payload.removedindex].key || item.key === '/')
          break
        case 'all':
          state.tabsList = state.tabsList.filter(item => item.key === '/')
          router.navigate('/', { replace: true })
          break
        default:
          state.tabsList.splice(payload.removedindex, 1)
          const tab = state.tabsList[payload.removedindex - 1]
          router.navigate(tab.path, { replace: true })
          break;
      }
    }
  },
})

export const { add, remove } = tabSlice.actions;
export default tabSlice.reducer;
